package com.cn.JUC.utils.case12;

import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Title 询价系统
 * @Description 对商品进行询价：开3个子线程，访问3个电商系统，先返回结果的，先保存到数据库，避免获取异步结果造成阻塞。
 * @Author CAI ZHAI
 * @Date 2021/9/9 14:33
 **/
public class InquiryPriceImpl{
    
    private void inquiryPrice() throws Exception{
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 创建CompletionService
        CompletionService<Integer> cs = new ExecutorCompletionService<>(executor);
        // 异步向电商S1询价
        cs.submit(()->getPriceByS1());
        // 异步向电商S2询价
        cs.submit(()->getPriceByS2());
        // 异步向电商S3询价
        cs.submit(()->getPriceByS3());
        // 将询价结果异步保存到数据库
        for (int i=0; i<3; i++) {
            Integer r = cs.take().get();
            executor.execute(()->save(r));
        }
    }
    
    //保存价格到数据库
    private void save(Integer r){
    }
    //询价电商平台3
    private Integer getPriceByS3(){
        return null;
    }
    //询价电商平台2
    private Integer getPriceByS2(){
        return null;
    }
    //询价电商平台1
    private Integer getPriceByS1(){
        return null;
    }
}
